import type {
  TableColumnProps,
  ProSaasTableExposeType,
  ColumnsSpanType
} from '~/components/ProSaasTable/typings'
import type { LoopSwitchGroupModalFormValuesType } from '../components/typings'
import type { LoopSwitchGroupInfoDataItemType } from './typings'
import { defineComponent, ref, reactive, watch, nextTick, onMounted } from 'vue'
// import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import {
  ElCard,
  ElLink,
  ElSpace,
  ElButton,
  ElFormItem,
  ElSelect,
  ElOption,
  ElInput,
  ElMessage,
  ElIcon,
  ElMessageBox
} from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { handleTrim } from '~/utils/util'
import ProSaasTable from '~/components/ProSaasTable'
import AliIcon from '~/components/AliIocn'
import ChangeLoopGroupModal from '../components/ChangeLoopGroupModal'
import useVuexGetters from '~/hooks/useVuexGetters'
import styles from '../../index.module.scss'
import DeviceAddTree from '../components/DeviceAddTree'
import websock from '~/utils/socket'

export default defineComponent(function LoopSwitchGroupContent() {
  // const router = useRouter()
  const store = useStore()
  const proSaasTableRef = ref<ProSaasTableExposeType>()
  const changeLoopGroupDetailRef = ref<LoopSwitchGroupModalFormValuesType>({})
  const formValues = reactive<LoopSwitchGroupInfoDataItemType>({})
  const userState = useVuexGetters('user', ['permission'])
  const loopSwitchGroupState = useVuexGetters('loopSwitchGroup', [
    'activeLoopGroupId',
    'loopSwitchSelectList'
  ])
  const state = reactive({
    taskStatusOpt: [
      { dictValue: '未发送', dictKey: 0 },
      { dictValue: '已下发', dictKey: 1 },
      { dictValue: '已成功', dictKey: 2 },
      { dictValue: '失败', dictKey: 3 }
    ],
    DeviceAddTreeVisible: false
  })

  // 按回车搜索列表
  const handleKeyDownEnterSearchList = (evt: Event | KeyboardEvent) => {
    if ((evt as KeyboardEvent).key === 'Enter') nextTick(proSaasTableRef.value!?.toSearch)
  }

  // 根据变更查询列表数据
  const handleChangeValueActionSearchList = () => {
    nextTick(proSaasTableRef.value!?.toSearch)
  }

  // 关闭变更分组弹框并搜索
  const handleCloseChangeLoopGroupModal = () => {
    changeLoopGroupDetailRef.value = {}
    proSaasTableRef.value!?.toSearch()
  }

  // 召测
  const handleCellTesting = async (record?: LoopSwitchGroupInfoDataItemType) => {
    if (record?.taskType === -1 || record?.taskType === null) {
      ElMessage({ type: 'warning', message: '设备回路未下发任务!' })
      return
    }
    const { data } = await store.dispatch('loopSwitchGroup/GetModelByDeviceIdGet', {
      id: record?.deviceId
    })
    const name = data.name

    const userInfo: any = localStorage.getItem('saber-userInfo')
    const token = JSON.parse(userInfo).content.accessToken
    // type = 1 周设置 D00040 & type = 2 多时段 D00041 & type = 2 全天 D00042
    let commandId = ''
    if (name === 'ZL_S01') {
      if (record?.taskType === 1) {
        commandId = 'D02018'
      } else if (record?.taskType === 2) {
        commandId = 'D02019'
      } else {
        commandId = 'D02020'
      }
    } else if (name === 'WL_S01') {
      if (record?.taskType === 1) {
        commandId = 'D00040'
      } else if (record?.taskType === 2) {
        commandId = 'D00041'
      } else {
        commandId = 'D00042'
      }
    }
    const actions: any = {
      deviceId: record?.deviceId,
      commandId,
      token
    }
    websock.send(JSON.stringify(actions))
    const params = {
      deviceId: record?.deviceId,
      commandId
    }
    store.dispatch('runmap/ExcuteCommandParamPost', params)
  }

  // 过滤table数据
  const handleFilterTableData = (
    filterData: LoopSwitchGroupInfoDataItemType[]
  ): LoopSwitchGroupInfoDataItemType[] => {
    const filterSettings: Record<string, ColumnsSpanType> = {}
    return filterData.map((item) => {
      if (item?.deviceId && !filterSettings[item?.deviceId]) {
        filterSettings[item?.deviceId] = {
          rowspan: 1,
          colspan: 1
        }
        return {
          ...item,
          filterSettings: filterSettings[item?.deviceId]
        }
      } else {
        if (filterSettings?.[item?.deviceId!]) filterSettings[item.deviceId!].rowspan!++
        return {
          ...item,
          filterSettings: {
            rowspan: 0,
            colspan: 0
          }
        }
      }
    })
  }
  //  删除
  const del = (row: any) => {
    const ids = row.id
    delAjax(ids, true)
  }
  //  删除多个
  const delMultiple = () => {
    const ids = proSaasTableRef.value!.selecteds?.map?.((item) => item!?.id)?.join(',')
    if (!ids) {
      ElMessage({ type: 'warning', message: '请勾选数据' })
      return
    }
    delAjax(ids, false)
  }
  //  删除请求
  const delAjax = (ids: any, value: boolean) => {
    ElMessageBox({
      title: '确认提示',
      message: (
        <section class={styles['delete-confirm-box']}>
          {value && <p class="delete-title">确认删除数据?</p>}
          {!value && (
            <p class="delete-title">
              {proSaasTableRef.value!.selecteds?.length > 1
                ? `确认删除选中的${proSaasTableRef.value!.selecteds?.length}条数据?`
                : '确认删除选中数据？'}
            </p>
          )}
          <p class="delete-content">删除后不可恢复，是否确认删除。</p>
        </section>
      ),
      showCancelButton: true,
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      closeOnClickModal: false, // 点遮罩层不关弹窗
      draggable: true // 可拖拽
    }).then(async () => {
      const { code } = await store.dispatch('loopSwitchGroup/GroupLoopRemoveApplyPost', { ids })
      if (code === 200) {
        proSaasTableRef.value!?.clearSelection?.()
        proSaasTableRef.value!?.toSearch()
        ElMessage({ type: 'success', message: '操作成功' })
      }
    })
  }
  //  应用
  const handleApplication = async () => {
    const ids = proSaasTableRef.value!.selecteds?.map?.((item) => item!?.id)?.join(',')
    if (!ids) {
      ElMessage({ type: 'warning', message: '请勾选数据' })
      return
    }
    const { code } = await store.dispatch('loopSwitchGroup/GroupLoopApplyListPost', { ids })
    if (code === 200) {
      proSaasTableRef.value!?.clearSelection?.()
      proSaasTableRef.value!?.toSearch()
      ElMessage({ type: 'success', message: '操作成功' })
    }
  }
  //  新增关闭
  const DeviceAddTreeCancel = () => {
    state.DeviceAddTreeVisible = !state.DeviceAddTreeVisible
    !state.DeviceAddTreeVisible && proSaasTableRef.value!?.toSearch()
  }

  watch(
    () => loopSwitchGroupState?.activeLoopGroupId?.value,
    () => {
      nextTick(proSaasTableRef.value!?.toSearch)
    }
  )

  onMounted(() => {
    if (!loopSwitchGroupState.loopSwitchSelectList.value?.length) {
      store.dispatch('loopSwitchGroup/GetLoopSwitchSelectList')
    }
    websock.onopen('/websocket/protocol/hardware')
  })

  const columns: TableColumnProps<LoopSwitchGroupInfoDataItemType>[] = [
    {
      label: '设备名称',
      prop: 'deviceName',
      showOverflowTooltip: true
    },
    // {
    //   label: '设备uid',
    //   prop: 'id',
    //   showOverflowTooltip: true
    // },
    {
      label: '回路名称',
      prop: 'loopName',
      showOverflowTooltip: true
    },
    {
      label: '任务名称',
      prop: 'taskName',
      showOverflowTooltip: true
    },
    {
      label: '任务状态',
      prop: 'taskStatus',
      showOverflowTooltip: true,
      render: ({ row }) => (
        <>
          {row.taskStatus === 0 && '未发送'}
          {row.taskStatus === 1 && '已下发'}
          {row.taskStatus === 2 && '已成功'}
          {row.taskStatus === 3 && '失败'}
        </>
      )
    },
    {
      label: '任务发送时间',
      prop: 'taskTime',
      showOverflowTooltip: true
    },
    {
      label: '操作',
      prop: 'options',
      align: 'center',
      width: 270,
      render: ({ row }) => (
        <ElSpace>
          {userState.permission.value.has('monitor_task_taskgroup_move') && (
            <ElLink type="primary" icon={<AliIcon type="icon-shanchu" />} onClick={() => del(row)}>
              删除
            </ElLink>
          )}
          <ElLink
            type="primary"
            icon={<AliIcon type="icon-lishirenwu1" />}
            onClick={() => handleCellTesting(row)}
          >
            召测
          </ElLink>
        </ElSpace>
      )
    }
  ]
  return () => (
    <ElCard class={[styles['loop-group-content'], 'covered-with-content']}>
      <ProSaasTable<LoopSwitchGroupInfoDataItemType>
        tableId="loopSwitchGroup"
        ref={proSaasTableRef}
        columns={columns}
        rowKey="id"
        hasSelection
        useGridLayout={false}
        filterTableDataMethod={handleFilterTableData}
        spanMethod={({ row, column }) =>
          column.property === 'deviceName' ? row.filterSettings! : { rowspan: 1, colspan: 1 }
        }
        dispatchType="loopSwitchGroup/GetMonitorGroupLoopList"
        searchParams={{
          taskGroupId: loopSwitchGroupState?.activeLoopGroupId?.value,
          loopName: formValues.loopName,
          deviceName: formValues.deviceName && handleTrim(formValues.deviceName)
        }}
        searchFormProps={{
          model: formValues
        }}
        searchformResponsiveCol={[
          <ElFormItem key="deviceName" prop="deviceName">
            <ElInput
              v-model={formValues.deviceName}
              placeholder="设备名称"
              clearable
              onKeydown={handleKeyDownEnterSearchList}
            />
          </ElFormItem>,
          <ElFormItem key="taskStatus" prop="taskStatus">
            <ElSelect
              v-model={formValues.taskStatus}
              placeholder="任务状态"
              clearable
              onChange={handleChangeValueActionSearchList}
            >
              {state.taskStatusOpt?.map((item) => (
                <ElOption key={item?.dictKey} label={item?.dictValue} value={item?.dictKey!} />
              ))}
            </ElSelect>
          </ElFormItem>
        ]}
        headerTitle={
          <>
            {userState.permission.value.has('monitor_task_taskgroup_move') && (
              <ElButton type="primary" onClick={DeviceAddTreeCancel}>
                <ElIcon>
                  <Plus />
                </ElIcon>
                &nbsp; 新增
              </ElButton>
            )}
            {userState.permission.value.has('monitor_device_remove') && (
              <ElButton type="danger" onClick={delMultiple}>
                <AliIcon type="icon-shanchu" />
                &nbsp; 删除
              </ElButton>
            )}
            {userState.permission.value.has('monitor_device_export') && (
              <ElButton type="success" onClick={handleApplication}>
                <AliIcon type="icon-daochu" />
                &nbsp; 应用
              </ElButton>
            )}
          </>
        }
      ></ProSaasTable>
      {changeLoopGroupDetailRef.value.taskGroupLoopIds && (
        <ChangeLoopGroupModal
          visible={!!changeLoopGroupDetailRef.value?.taskGroupLoopIds}
          detail={changeLoopGroupDetailRef.value}
          cancel={handleCloseChangeLoopGroupModal}
        />
      )}
      {state.DeviceAddTreeVisible && (
        <DeviceAddTree visible={state.DeviceAddTreeVisible} cancel={() => DeviceAddTreeCancel()} />
      )}
    </ElCard>
  )
})
